let http = require('http');
let https = require('https');
let fs = require('fs');
const unzipper = require('unzipper');
let querystring = require('querystring');


//2.auth路由：接受code,用code+client_id+client_secret换取token

function auth(request, response) {
    let query = querystring.parse(request.url.match(/^\/auth\?([\s\S]+)$/)[1]);
    getToken(query.code, (info) => {
        response.write(`<a href='http://localhost:8082/?token=${info.access_token}'>publish</a>`);
        response.end();
    });
}

function getToken(code, callback) {
    let request = https.request({
        hostname: 'github.com',
        path: `/login/oauth/access_token?code=${code}&client_id=Iv1.f8d020e613db0d43&client_secret=3547c39a194b314448122648ba514c472a6f847a`,
        port: 443,
        method: 'POST',
    }, (response) => {
        let body = "";
        response.on('data', chunk => {
            body += chunk.toString();
        });
        response.on('end', () => {
            let o = querystring.parse(body);
            callback(o);
        });
    });
    request.end();
}

//4.publish路由：用token获取用户信息，检查权限，接受发布

function publish(request, response) {
    let query = querystring.parse(request.url.match(/^\/publish\?([\s\S]+)$/)[1]);

    if (query.token) {
        getUser(query.token, (info) => {
            console.log(info);
            if (info.login === 'flttx') {
                request.pipe(unzipper.Extract({ path: '../server/public/' }));
                request.on('end', () => {
                    response.end('Publish Success');
                });
            }
        });
    }

}

function getUser(token, callback) {
    let request = https.request({
        hostname: 'api.github.com',
        path: `/user`,
        port: 443,
        method: 'GET',
        headers: {
            'Authorization': `token ${token}`,
            'User-Agent': 'xq-publish',
        },  
    }, (response) => {
        let body = "";
        response.on('data', chunk => {
            body += chunk.toString();
        });
        response.on('end', () => {
            callback(JSON.parse(body));
        });
    });
    request.end();
}



http.createServer((request, response) => {
    // console.log(request.headers);
    if (request.url.match(/^\/auth\?/)) {
        return auth(request, response);
    }
    if (request.url.match(/^\/publish\?/)) {
        return publish(request, response);
    }

    // 创建可写流
    // let outFile = fs.createWriteStream('../server/public/tmp.zip');

    // request.pipe(outFile);

    // request.pipe(unzipper.Extract({ path: '../server/public/' }));

    request.on('end', () => {
        response.end('Success');
    });

    // request.on('data', chunk => {
    //     outFile.write(chunk);
    // });
    // request.on('end', () => {
    //     outFile.end();
    //     response.end('Success');
    // });
   
}).listen(8081);